package com.itheima.health.controller;

import com.itheima.health.common.MessageConst;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.Member;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.SmsService;
import com.itheima.health.vo.SmsLoginParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

/**
 * @author tian
 * @TIME 2023/1/5 5:55 下午
 * @description 登录验证Controller
 */
@Slf4j
@RestController
@RequestMapping("/mobile/login")
public class MobileLoginController {
    @Autowired
    private SmsService smsService;
    @Autowired
    private MemberService memberService;

    /**
     * 登录验证
     *
     * @param smsLoginParam 手机号验证码
     * @return
     */
    @RequestMapping("/smsLogin")
    public Result smsLogin(@RequestBody SmsLoginParam smsLoginParam, HttpServletRequest request) {
        log.info("[登录验证]smsLoginParam:{}", smsLoginParam);
        //验证码校验
        boolean flag = smsService.checkValidateCode("MOBILE_SIGNIN", smsLoginParam.getTelephone(), smsLoginParam.getValidateCode());
        if (!flag) {
            return new Result(flag, MessageConst.LOGIN_FAIL);
        }
        //判断该手机号会员是否存在，不存在则注册为会员
        Member member = new Member();
        member.setPhoneNumber(smsLoginParam.getTelephone());
        member = memberService.isCreate(member);
        request.getSession().setAttribute("member", member);
        //登录（模拟，直接输出成功）
        log.info("[登录成功]》》》》》》》》》》》id:{}", member.getId());
        return new Result(true, MessageConst.LOGIN_SUCCESS);
    }
}
